package com.qdxwx.web.controller.picture;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.picture.PictureAlbumService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.channel.Channel;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.models.picture.PictureAlbum;
import com.qdxwx.models.picture.PictureQuery;
import com.qdxwx.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/picture")
public class PictureListController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(PictureListController.class);

    @Autowired
    private ChannelService channelService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private PictureAlbumService pictureAlbumService;

    @RequestMapping({"/list.html","/index.html"})
    public String showCourseIndex(HttpServletRequest request, ModelMap model) {
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"),31);
        if (TKRequest.isMobileBrowse(request)){
            model.put("categoryId",categoryId);
            return getViewPathH5("picture/picture-list");
        }
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (channelId == 0) {
            channelId = 10;
        }
        int albumId = TKConvert.toInteger(request.getParameter("albumId"));
        if (albumId > 0) {
            PictureAlbum album = pictureAlbumService.get(albumId);
            if (album == null) {
                return toError404(request);
            }
            categoryId = album.getCategoryId();
        }
        //  int subjectId = TKConvert.toInteger(request.getParameter("subjectId"));
        int categoryRootId = 0;
        int categoryParentId = 0;
        int categoryChildCount = 0;
        String pageTitle = "素材";
        if (categoryId > 0) {
            Category category = categoryService.get(categoryId);
            if (category == null) {
                categoryId = 0;
            } else {
                channelId = category.getChannelId();
                if (category.getParentId() == 0) {
                    categoryRootId = categoryId;
                } else {
                    categoryRootId = category.getParentId();
                }
                categoryParentId = category.getParentId();
                categoryChildCount = category.getChildCount();
                pageTitle = category.getCategoryName() + "-" + pageTitle;
                model.put("category", category);
            }
        }
        Channel channel = channelService.get(channelId);
        if (channel == null) {
            return toError404(request);
        }
        //禁用的频道
        if (channel.getIsDisabled() == 1) {
            return toError404(request);
        }
        //判断是否属于模块
        if (channel.getModuleId() != ModuleType.PICTURE.ordinal()) {
            return toError404(request);
        }

        // 查询所有1级专业
        List<Category> categoryRoots = categoryService.getRoots(channelId);
        model.put("categoryRoots", categoryRoots);
        //查询子专业
        if (categoryId > 0) {
            List<Category> categoryChildren;

            //父Id大于0,获得它的同级专业
            if (categoryParentId <= 0) {
                //获得它的子级专业
                categoryChildren = categoryService.getChildren(categoryId);
            } else {
                Category parent = categoryService.get(categoryParentId);
                if (parent == null) {
                    logger.error("找不到对应父分类（categoryId:" + categoryId + ",parentId:" + categoryParentId + "）");
                    return toErrorView(request, "找不到对应的分类！" + categoryParentId);
                }
                //标题
                pageTitle = parent.getCategoryName() + "-" + pageTitle;
                List<Category> categorySons;
                if (parent.getParentId() <= 0) {
                    //category是二级
                    categoryChildren = categoryService.getChildren(categoryParentId);
                    categorySons = categoryService.getChildren(categoryId);
                    categoryParentId = categoryId;
                } else {
                    //说明category是三级
                    categoryRootId = parent.getParentId();
                    Category root = categoryService.get(categoryRootId);
                    if (root == null) {
                        logger.error("找不到对应父分类（categoryId:" + categoryId + ",parentId:" + categoryParentId + "）");
                        return toErrorView(request, "找不到对应的分类！" + categoryParentId);
                    }
                    pageTitle = root.getCategoryName() + "-" + pageTitle;
                    categoryChildren = categoryService.getChildren(categoryRootId);
                    categorySons = categoryService.getChildren(categoryParentId);
                }
                model.put("categorySons", categorySons);
                model.put("categoryParent", parent);//父级 专业名
            }
            model.put("categoryChildren", categoryChildren);
        }
        model.put("pageTitle", pageTitle);
        model.put("categoryRootId", categoryRootId);//一级Id
        model.put("categoryParentId", categoryParentId);//父级id
        model.put("categoryId", categoryId);//id
        int page = TKConvert.toInteger(request.getParameter("page"), 1);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setCurrentPage(page);
        pageRequest.setPageSize(20);

        PictureQuery params = new PictureQuery();
        params.setAlbumId(albumId);
        params.setCategoryId(categoryId);
        params.setOrderBy(TKConvert.toInteger(request.getParameter("orderBy"),3));
        params.setIsFree(TKConvert.toInteger(request.getParameter("isFree")));
        params.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));

        List<Picture> pictureList;
        int total = 5760;//未指定类别，最多显示5760;
        if (categoryId > 0 && albumId == 0) {
            params.setCategoryIds(categoryService.getChildIds(categoryId));
        }
        pictureList = pictureService.getList(params, pageRequest);
        if (categoryId > 0) {
            total = pictureService.count(params);
        }
        //第一页显示专辑
        /*
        if (page == 1) {
            PictureAlbum pictureAlbum = new PictureAlbum();
            pictureAlbum.setCategoryId(categoryId);
            pictureAlbum.setIsElite(1);
            List<PictureAlbumVo> pictureAlbumVoList = pictureAlbumService.getListVo(pictureAlbum, new PageRequest(1, 4));
            model.put("pictureAlbumVoList", pictureAlbumVoList);
        }*/
        if (categoryId > 0 && categoryChildCount == 0) {
            model.put("pictureAlbums", pictureAlbumService.getList(categoryId, 0));
        }
        model.put("channel", channel);
        model.put("params", params);
        model.put("pictureList", pictureList);
        model.put("totalPages", pageRequest.getTotalPages(total));
        model.put("page", pageRequest);
        return getViewPath("picture/picture-list");
    }
}
